package com.itheima.utils;

import java.util.Calendar;
import java.util.Date;

public class TransferIdUtils {
    /**
     * 将15位身份证号转化为18位返回，非15位身份证号原值返回
     * @param identityCard
     * @return
     */
    public static String get18Ic(String identityCard) {
        String retId = "";
        String id17 = "";
        int sum = 0;
        int y = 0;
        // 定义数组存放加权因子（weight factor）
        int[] wf = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };
        // 定义数组存放校验码（check code）
        String[] cc = { "1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2" };
        if (identityCard.length() != 15) {
            return identityCard;
        }
        // 加上两位年19
        id17 = identityCard.substring(0, 6) + "19" + identityCard.substring(6);
        // 十七位数字本体码加权求和
        for (int i = 0; i < 17; i++) {
            sum = sum + Integer.valueOf(id17.substring(i, i + 1)) * wf[i];
        }
        // 计算模
        y = sum % 11;
        // 通过模得到对应的校验码 cc[y]
        retId = id17 + cc[y];
        return retId;
    }

    //获取当前时间
    public static int getAgeByBirth(Date birthday) {
        int age = 0;
        try {
            Calendar now = Calendar.getInstance();
            now.setTime(new Date());// 当前时间

            Calendar birth = Calendar.getInstance();
            birth.setTime(birthday);

            if (birth.after(now)) {//如果传入的时间，在当前时间的后面，返回0岁
                age = 0;
            } else {
                age = now.get(Calendar.YEAR) - birth.get(Calendar.YEAR);
                if (now.get(Calendar.DAY_OF_YEAR) > birth.get(Calendar.DAY_OF_YEAR)) {
                    age += 1;
                }
            }
            return age;
        } catch (Exception e) {//兼容性更强,异常后返回数据
            return 0;
        }
    }

    public static String getSex(String id){
        int sexNumber=Integer.parseInt(id.substring(16, 17));
        if (sexNumber%2==0){
            return "2";
        }
        return "1";
    }

    public static String getBirthday(String id){
        String year=id.substring(6,10);
        String month=id.substring(10,12);
        String day=id.substring(12,14);

        return year+"-"+month+"-"+day;
    }

    public static void main(String[] args) {
        //测试
        System.out.println(get18Ic("132333333333333"));
        System.out.println(getSex(get18Ic("132333333333333")));
        System.out.println(getBirthday("511023199507045934"));
    }
}
